/**
 * Created by cacalot123 on 2016/4/19.
 */
(function ($) {
    "use strict";
    /***** 变量定义  *****/
    var $userAddress = $("#userAddressList"),
        $userAddressList = $("#userAddressList li"),
        $hideAddress = $("#hideAddress"),
        flagClass,
        $j_cellphoneNo = $(".j_cellphoneNo"),
        $j_distributionInfoError = $(".j_distributionInfoError"),
        $j_invoiceContentUl = $(".j_invoiceContentUl"),
        $j_invoiceLi1 = $(".j_invoiceLi1"),
        $j_invoiceLi2 = $(".j_invoiceLi2"),
        $j_icon1 = $j_invoiceLi1.find(".icon"),
        $j_icon2 = $j_invoiceLi2.find(".icon"),
        $j_invoiceContentInput = $(".j_invoiceContentInput"),
        $j_invoiceContentPosError = $(".j_invoiceContentPosError"),
        $add_address = $(".add_address"),
        $userAddressListEdit = $userAddressList.find(".edit");


    /***** 方法定义  *****/
    var addressManage = {
        currentAddress: function () {
            $userAddressList.on("click", function () {
                var $self = $(this);
                $userAddressList.removeClass("current active");
                $self.addClass("current");
            })
        },
        showAllAddress: function () {
            if ($userAddressList.length <= 4) {
                $hideAddress.hide();
            } else {
                flagClass = $hideAddress.find("i").attr("class");

                if (flagClass == "open") {//展开
                    $hideAddress.find("i").attr("class", "close");
                    $userAddress.addClass("address_open");
                    // $userAddressList.show();
                    $hideAddress.find("span").html("收起地址");
                } else if (flagClass == "close") {//收起
                    $hideAddress.find("i").attr("class", "open");
                    $userAddress.removeClass("address_open");
                    $hideAddress.find("span").html("更多地址");
                    $userAddress.find(".current").show();
                }
            }
        }
    }
    var detailInfoManage = {
        verifyCellphoneNo: function () {
            $j_cellphoneNo.val($j_cellphoneNo.val().replace(/\D/g, ''));
        },
        showCellphoneNoError: function () {
            if ($j_cellphoneNo.val().length === 0) {
                $j_cellphoneNo.addClass("active");
                $j_distributionInfoError.show();
            }
        },
        hideCellphoneNoError: function () {
            $j_cellphoneNo.removeClass("active");
            $j_distributionInfoError.hide();
        },
        showInvoiceContentUl: function () {
            $j_invoiceContentUl.show();
            $j_icon1.removeClass("checked");
            $j_icon2.addClass("checked");
        },
        hideInvoiceContentUl: function () {
            $j_invoiceContentUl.hide();
            $j_icon1.addClass("checked");
            $j_icon2.removeClass("checked");
        },
        showInvoiceContentPosError: function () {
            if ($j_invoiceContentInput.val().length === 0) {
                $j_invoiceContentInput.addClass("active");
                $j_invoiceContentPosError.show();
            }
        },
        hideInvoiceContentPosError: function () {
            $j_invoiceContentInput.removeClass("active");
            $j_invoiceContentPosError.hide();
        }
    }
    // 弹层
    var showModal = {
        createAlertBox: function (data) {
            var consigneeInfo = null,
                consigneeInfoRow = null,
                consigneeInfoColumnLeft = null,
                consigneeInfoColumnRight = null,
                consigneeInfoErrorSpan = null,
                consigneeInfoAddress = null,
                consigneeInfoBtn = null;

            consigneeInfo = $("<div>").addClass("consigneeInfoContainer");
            for (var i = 0; i < data.desc.length; i++) {
                consigneeInfoRow = $("<div>").addClass("consigneeInfoRow");
                consigneeInfoColumnLeft = $("<div>").addClass("consigneeInfoColumnLeft")
                    .append($("<span>").addClass("asterisk").text("*"))
                    .append($("<span>").addClass("consigneeInfoDesc").text(data.desc[i]));
                if (i === 1) {
                    consigneeInfoAddress = $("<select>").addClass(data.consigneeInfoClass[i]);
                    for (var j = 0; j < data.addressData.length; j++) {
                        consigneeInfoAddress.append($("<option>").text(data.addressData[j]));
                    }
                    consigneeInfoColumnRight = $("<div>").addClass("consigneeInfoColumnRight")
                        .append(consigneeInfoAddress);
                }
                else {
                    consigneeInfoErrorSpan = $("<span>").addClass("consigneeInfoErrorSpan")
                        .append($("<i>").addClass("ECar_icon_warn consigneeInfoIcon"))
                        .append($("<span>").addClass("consigneeInfoWarning").text(data.warning[i]));
                    consigneeInfoColumnRight = $("<div>").addClass("consigneeInfoColumnRight")
                        .append($("<input>").addClass(data.consigneeInfoClass[i]).attr("type", "text")).data("validation", data.validation[i])
                        .bind("keyup", function () {
                            var $self = $(this),
                                $input = $self.find("input"),
                                re,
                                val = $input.val();
                            re = new RegExp($self.data("validation"));
                            if (re.test(val)) {
                                $input.next(".consigneeInfoErrorSpan").show();
                            } else {
                                $input.next(".consigneeInfoErrorSpan").hide();
                            }
                        })
                        .append(consigneeInfoErrorSpan);
                }

                consigneeInfoRow.append(consigneeInfoColumnLeft);
                consigneeInfoRow.append(consigneeInfoColumnRight);
                consigneeInfo.append(consigneeInfoRow);
            }
            consigneeInfoBtn = $("<div>").addClass("ECar_modal_button")
                .append($("<button>").addClass("save consigneeInfoBtn").text("保存收货人信息"));
            consigneeInfo.append(consigneeInfoBtn);
            return consigneeInfo;
        },
        setConsigneeInfo: function () {
            /*
             var data={
             desc:['收货人：','所在地区：','详细地址：','手机号码：'],
             warning:['收货人不能为空','','地址不能为空','手机号码不能为空'],
             consigneeInfoClass:['person','district','address','phoneNo'],
             addressData:['上海长宁区城区','上海长宁区城区','上海长宁区城区'],
             validation:[/^\s*$/g,/^\s*$/g,/^\s*$/g,/^\s*$/g]
             };



             var consigneeInfo=this.createAlertBox(data);
             */

            var layerAaddressHtml;
            layerAaddressHtml = $("#consigneeInfoContainer").html();
            if (!$("body").attr("data-layerHtml")) {
                $("body").attr("data-layerHtml", layerAaddressHtml);
            }

            ECar.modal.otherTemplate({
                width: 690,
                height: 295,
                title: "新增收款人信息",
                maskAlpha: "1",
                template: $("body").attr("data-layerHtml")
            });
            $("#consigneeInfoContainer").remove();

        },

        validation: function () {
            var formValidation =
                {
                    "box": "userAddressList",
                    "list": [
                        {"label": "收货人", "id": "consigneeInfoName","rule": ["isEmpty", "isChineseOrEnglish"]},
                        {"label": "所在地区", "id": "consigneeInfoCity","rule": "isEmpty"},
                        {"label": "详细地址", "id": "consigneeInfoAddress", "rule": ["isEmpty"]},
                        {"label": "手机号码", "id": "consigneeInfoPhone", "rule": ["isEmpty", "isMobile"]}
                    ],
                    "submit": ".consigneeInfoBtn"
                },
                $valInput,
                $submit = $(formValidation.submit);
            //根据规则进行显示
            function ruleCheck(rule, obj) {
                var ruleFunction,
                    $input = obj.input,
                    $tips = obj.tips,
                    label = obj.label,
                    $tipsTxt = $tips.find(".consigneeInfoWarning"),
                    val = $input.val();
                $.each(rule, function (i) {
                    switch (rule[i]) {
                        case "isEmpty":
                            ruleFunction = !ECar.reg.isEmpty(val);
                            $tipsTxt.html("请您填写" + label);
                            break;
                        case "isMobile":
                            ruleFunction = ECar.reg.isMobile(val);
                            $tipsTxt.html(label + "格式不正确");
                            break;
                        case "isChineseOrEnglish":
                            var re = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
                            ruleFunction = val.match(re);
                            $tipsTxt.html(label + "含有非法字符");
                            break;
                        default:
                            ruleFunction = '';
                    }

                    if (!ruleFunction) {
                        return false
                    }
                })
                if (ruleFunction) {
                    $tips.hide();
                    $input.attr("data-flag", "ok");
                } else {
                    $tips.show();
                    $input.attr("data-flag", "fail");
                }

            }

            for (var i = 0; i < formValidation.list.length; i++) {
                var list = formValidation.list[i],
                    listRule = list.rule,
                    listLabel = list.label;
                if (!list.input) {
                    $valInput = $("#" + list.id).find("input");

                } else {
                    $valInput = $(list.input);
                }
                $("#" + list.id).data({
                    "data-rule": listRule,
                    "data-label": listLabel
                });
                $("#" + list.id + " input").on("keyup blur", function () {
                    var $self = $(this),
                        $tips = $self.next(".consigneeInfoErrorSpan"),
                        label = $self.closest(".consigneeInfoRow").data("data-label"),
                        listRule = $self.closest(".consigneeInfoRow").data("data-rule");

                    ruleCheck(listRule, {
                        label: label,
                        input: $self,
                        tips: $tips
                    });

                })

                /*
                 if (list.rule == "isEmpty") {
                 $("#" + list.id + " input").on("keyup blur", function () {
                 var $self = $(this),
                 $tips = $self.next(".consigneeInfoErrorSpan");

                 if(ECar.reg.isEmpty($self.val())){
                 $tips.show();
                 $self.attr("data-flag","fail");
                 }else{
                 $tips.hide();
                 $self.attr("data-flag","ok");

                 };
                 //console.log(flag[i]+"-"+i)
                 })
                 }else  if (list.rule == "isMobile") {
                 $("#" + list.id + " input").bind("keyup blur", function () {
                 var $self = $(this),
                 $tips = $self.next(".consigneeInfoErrorSpan");
                 if(!ECar.reg.isMobile($self.val())){
                 $tips.show();
                 $self.attr("data-flag","fail");
                 }else{
                 $tips.hide();
                 $self.attr("data-flag","ok");
                 };
                 })
                 }*/
            }
            showModal.sumbitLayer(formValidation);


        },
        sumbitLayer: function (formValidation) {
            //弹层关闭事件
            function closeLayer(layerType, forminfo) {
                var layerType = layerType,
                    userInfo = forminfo,
                    htmlList = "";

                htmlList = '<label class="address_tips"><span class="add_name">' + userInfo.name + '</span><span class="add_city">上海</span></label>' +
                    '<div class="address_detailed"><span class="address_name">' + userInfo.name + '</span><span class="address_info">' + userInfo.address_info + '</span><span class="address_tel">' + userInfo.tel + '</span></div>' +
                    '<div class="handle"><span class="default_address">设为默认地址</span><span class="edit">编辑</span><span class="del">删除</span></div>';
                layerType = $(".ECar_modal_mask").attr("data-layerType");

                function reEditLayer(obj) {
                    var $thisline = obj.closest("li"),
                        index = $thisline.index();
                    showModal.editLayer($thisline);
                    $(".ECar_modal_mask").attr(
                        {
                            "data-layerType": "editAddress",
                            "data-lineIndex": index
                        });
                    return false;
                }

                if (layerType == "addAddress") {
                    $("<li>" + htmlList + "</li>").appendTo("#userAddressList ul").on("click", function () {
                        var $self = $(this);
                        $userAddressList.removeClass("current");
                        $self.addClass("current");
                    }).end()
                        .find(".edit").on("click", function () {
                        var $self = $(this);
                        reEditLayer($self);
                    });
                } else if (layerType == "editAddress") {
                    var liIndex = $(".ECar_modal_mask").attr("data-lineIndex");
                    $("#userAddressList li").eq(liIndex).html(htmlList);
                    $("#userAddressList li").find(".edit").on("click", function () {
                        var $self = $(this);
                        reEditLayer($self);
                    });
                }
            }

            $(".consigneeInfoBtn").on("click", function () {
                var flag = true;
                for (var i = 0; i < formValidation.list.length; i++) {
                    var list = formValidation.list[i],
                        $input = $("#" + list.id).find("input");
                    $input.blur();
                    if ($input.length != 0) {
                        if ($input.attr("data-flag") != "ok") {
                            flag = false;
                            break;
                        }
                    }
                }
                if (flag) {//success
                    var addressInfo = {};
                    addressInfo.name = $("#consigneeInfoName input").val(),
                        addressInfo.address_info = $("#consigneeInfoAddress input").val(),
                        addressInfo.tel = $("#consigneeInfoPhone input").val();
                    closeLayer("add", addressInfo);
                    $(".ECar_modal_mask").hide();
                }
            })
        },
        editLayer: function (thisline) {
            this.setConsigneeInfo();
            var $thisline = thisline;
            var name = $thisline.find(".address_name").html(),
                city = $thisline.find(".address_city").html(),
                address = $thisline.find(".address_info").html(),
                tel = $thisline.find(".address_tel").html();

            $("#consigneeInfoName input").val(name);
            $("#consigneeInfoAddress input").val(address);
            $("#consigneeInfoPhone input").val(tel);
            showModal.validation();
        }
    }


    /***  方法调用  ****/
    addressManage.currentAddress();
    addressManage.showAllAddress();
    $hideAddress.on("click", function () {
        addressManage.showAllAddress();
    });
    //手机输入验证
    $j_cellphoneNo.on("input", function () {
        detailInfoManage.verifyCellphoneNo();
    });
    $j_cellphoneNo.on("blur", function () {
        detailInfoManage.showCellphoneNoError();
    });
    $j_cellphoneNo.on("focus", function () {
        detailInfoManage.hideCellphoneNoError();
    });
    //是否需要发票事件
    $j_invoiceLi1.on("click", function () {
        detailInfoManage.hideInvoiceContentUl();
    });
    $j_invoiceLi2.on("click", function () {
        detailInfoManage.showInvoiceContentUl();
    });
    //发票抬头验证
    $j_invoiceContentPosError.hide();
    $j_invoiceContentInput.on("blur", function () {
        detailInfoManage.showInvoiceContentPosError();
    });
    $j_invoiceContentInput.on("focus", function () {
        detailInfoManage.hideInvoiceContentPosError();
    });
    //弹处框展示
    $add_address.on("click", function () {
        showModal.setConsigneeInfo();
        showModal.validation();
        $(".ECar_modal_mask").attr("data-layerType", "addAddress");
    });

    $userAddressListEdit.on("click", function () {
        var $thisline = $(this).closest("li"),
            index = $thisline.index();
        showModal.editLayer($thisline);
        $(".ECar_modal_mask").attr(
            {
                "data-layerType": "editAddress",
                "data-lineIndex": index
            });
        return false;
    })
})(jQuery);